import React, { useState, useEffect, useLayoutEffect } from 'react'
import { Select, Space, Button, Row, Col, Switch, message, Spin } from 'antd'
import { SearchOutlined } from '@ant-design/icons';
import List from '../../../components/afterLoan/List';
import { WarningListAsyncAction, WarningUpdateAsyncAction, SetSpinningAction, SetPageSizeAction, SetCurrentPageAction } from '../../../store/afterLoanStore/action';
import { useDispatch, useSelector } from 'react-redux';
import { loanType, loanProduct, loanStage, loanPeriod } from '../../../utils/afterLoanUtils'
import { Link } from 'react-router-dom';
import { clearSpin } from '../../../utils/afterLoanUtils';
import Bread from '../../../components/Bread';

const { Option } = Select
let timer = null

// const data = [];
// for (let i = 0; i < 46; i++) {
//     data.push({
//         warning_num: i,
//         key: i,
//         warning_name: '预警名称',
//         loan_type: '贷款类型',
//         loan_product: '借款产品',
//         early_warning: '预警阶段',
//         early_day: '提前预警天数',
//         warning_cycle: '预警周期',
//         remind_time: '提醒时间',
//         send_method: '发送方式',
//     });
// }

export default function Warning({ history }) {
    const dispatch = useDispatch()
    const warningList = useSelector(state => state.afterLoanStore.warningList)
    const [WarningList, setWarningList] = useState([])
    const [loanafter_warningstage, setLoanafter_warningstate] = useState(null)
    const [loanafter_status, setLoanafter_status] = useState(null)
    // const spinning = useSelector(state => state.afterLoanStore.spinning)
    const pageSize = useSelector(state => state.afterLoanStore.pageSize)
    const currentPage = useSelector(state => state.afterLoanStore.currentPage)
    // console.log(warningList);
    // loanType(item.loanafter_loantype)
    // warning 列表

    const getWarningList = (currentPage = 1, pageSize = 10) => {
        dispatch(SetSpinningAction(true))
        // console.log(dispatch(SetSpinningAction(true)));
        // console.log();
        // console.log('info:', pageSize, currentPage);
        dispatch(WarningListAsyncAction({
            currentPage,
            pageSize,
            data: {
                loanafter_warningstage,
                loanafter_status
            }
        }))
            .then(res => {
                console.log(res);
            })
            .catch(err => {
                console.log(err);
                message.error("查询失败：", err)
            })
            .finally(() => {
                clearSpin(timer, dispatch)
            })
    }

    const searchSubmit = () => {
        dispatch(SetCurrentPageAction(1))
        dispatch(SetPageSizeAction(10))
        getWarningList()
    }


    useEffect(() => {
        if (warningList.length) {
            const warningArr = []
            warningList.forEach((item, index) => {
                const obj = {
                    ...item,
                    loanafter_loantype: loanType(item.loanafter_loantype),
                    loanafter_loanproduct: loanProduct(item.loanafter_loanproduct),
                    loanafter_warningstage: loanStage(item.loanafter_warningstage),
                    loanafter_warningperiod: loanPeriod(item.loanafter_warningperiod),
                    loanafter_sendmethod: '短信',
                    key: index
                }
                warningArr.push(obj)
            })
            setWarningList(warningArr)
            console.log(WarningList);
        } else {
            setWarningList([])
        }
    }, [warningList])

    useEffect(() => {
        getWarningList()
    }, [])



    // 表头
    const columns = [
        {
            title: '编号',
            dataIndex: 'loanafter_warning_id',
            key: 'loanafter_warning_id'
        },
        {
            title: '预警名称',
            dataIndex: 'loanafter_warningname',
            key: 'loanafter_warningname'
        },
        {
            title: '贷款类型',
            dataIndex: 'loanafter_loantype',
            key: 'loanafter_loantype'
        },
        {
            title: '借款产品',
            dataIndex: 'loanafter_loanproduct',
            key: 'loanafter_loanproduct'
        },
        {
            title: '预警阶段',
            dataIndex: 'loanafter_warningstage',
            key: 'loanafter_warningstage'
        },
        {
            title: '提前预警天数',
            dataIndex: 'loanafter_beforewarningdate',
            key: 'loanafter_beforewarningdate'
        },
        {
            title: '预警周期',
            dataIndex: 'loanafter_warningperiod',
            key: 'loanafter_warningperiod'
        },
        {
            title: '提醒时间',
            dataIndex: 'loanafter_sendwarningtime',
            key: 'loanafter_sendwarningtime'
        },
        {
            title: '发送方式',
            dataIndex: 'loanafter_sendmethod',
            key: 'loanafter_sendmethod'
        },
        {
            title: '启用状态',
            dataIndex: 'enabled',
            render: (text, record) => (
                <>
                    <Switch checkedChildren="开启" unCheckedChildren="关闭" checked={record.loanafter_status} onChange={
                        (value) => {
                            dispatch(SetSpinningAction(true))
                            dispatch(WarningUpdateAsyncAction({
                                loanafter_warning_id: record.loanafter_warning_id,
                                loanafter_status: Number(value)
                            }))
                                .then(res => {
                                    message.success(res)
                                    getWarningList(currentPage, pageSize)
                                })
                                .catch(err => {
                                    message.error('修改失败：', err)
                                    console.log(err);
                                })
                                .finally(() => {
                                    clearSpin(timer, dispatch)
                                })
                        }
                    } />
                </>
            )
        },
        {
            title: '操作',
            key: 'action',
            render: (text, record) => (
                <Space>
                    <Link to={{
                        pathname: '/home/afterloan/addwarning',
                        loanafter_warning_id: record.loanafter_warning_id,
                        state: 2
                    }}>查看</Link>
                    <Link to={{
                        pathname: '/home/afterloan/addwarning',
                        loanafter_warning_id: record.loanafter_warning_id,
                        state: 3,
                    }}>修改</Link>
                </Space>
            )
        }
    ];

    // Searcn 栏
    const Search = (
        <div className='after-search'>
            <Row gutter={{ xs: 8, sm: 16, md: 24, lg: 32 }}>
                <Col className="gutter-row" span={8}>
                    <div>
                        <Select
                            allowClear
                            value={loanafter_warningstage}
                            onChange={(value) => {
                                // console.log(value);
                                setLoanafter_warningstate(value)
                            }}
                            style={{ width: 100 }}
                            showSearch
                            placeholder="预警阶段"
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            <Option value={1}>即将到期</Option>
                            <Option value={2}>已经逾期</Option>
                            {/* <Option value="tom">Tom</Option> */}
                        </Select>
                    </div>
                </Col>
                <Col className="gutter-row" span={9}>
                    <div>
                        <Select
                            allowClear
                            onChange={(value) => {
                                setLoanafter_status(value)
                            }}
                            value={loanafter_status}
                            style={{ width: 100 }}
                            showSearch
                            placeholder="启用状态"
                            optionFilterProp="children"
                            filterOption={(input, option) =>
                                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                        >
                            <Option value={0}>关闭</Option>
                            <Option value={1}>开启</Option>
                        </Select>
                    </div>
                </Col>
                <Col className="gutter-row" span={7}>
                    <div>
                        <Button icon={<SearchOutlined />} type='button' onClick={searchSubmit}>
                            查询
                        </Button>
                    </div>
                </Col>
            </Row>
        </div >
    )

    return (
        <div className='warning'>
            <Bread bread_title1="贷后管理" bread_title2="贷后预警" />
            {Search}
            <List isAdd={true} columns={columns} data={WarningList} addUrl="/home/afterloan/addwarning" push={history.push} type="warning" searchCondition={
                { loanafter_warningstage, loanafter_status }
            } getWarningList={getWarningList} />
        </div>
    )
}
